//
//  ST_MemberSubscriberController.swift
//  btvideo
//
//  Created by mac on 2020/9/24.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON
import SwiftyAttributes
import MBProgressHUD

enum ST_BitianSubscribeType:Int,CaseIterable{
    
    case 无线喜欢次数 = 0
    case 查看谁喜欢我
    case 筛选最想看的人
    case 精准搜人
    case 开启隐身模式
    case 金色昵称
    case 专属标识
    case 位置漫游
}



class ST_MemberSubscriberController: UIViewController,ST_TIANPaymentTransactionStateDelegate {

    
    convenience init(subscribeType:ST_BitianSubscribeType,isMask:Bool = false) {
        self.init(nibName: nil, bundle: nil)
        
        var array = ST_MemberSubscriberItemViewStruct.normal_struct_datasource()
        
        array.swapAt(subscribeType.rawValue, 0)
        
        self.data_array = array
        
        animate_images.swapAt(subscribeType.rawValue, 0)
        
        self.isMaskView = isMask
        
    }
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    fileprivate let root_view_width = 345.cgFloat
    
    fileprivate var isMaskView = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        ST_BTGlobalDataCenter.shared.payMemberPage(paramValue: "页面曝光")
        
        view.backgroundColor = UIColor.init(white: 0, alpha: 0.5)
        
        if isMaskView {
            view.addSubview(personal_mask_view)
            personal_mask_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
        }
        
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.width.equalTo(root_view_width)
            make.height.equalTo(549)
            make.centerX.equalToSuperview()
            if iPhoneXSeries{
                make.centerY.equalToSuperview()
            }else{
                make.top.equalToSuperview().offset(statusBarHeight + 4)
            }
        }
        
        
        
        
        root_view.addSubview(animate_image_view1)
        animate_image_view1.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(179)
        }
        
        root_view.addSubview(animate_image_view0)
        animate_image_view0.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(179)
        }
        
        
        root_view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(233)
        }
        
        scrollView.addSubview(scroll_content_view)
        scroll_content_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(root_view_width*ST_BitianSubscribeType.allCases.count.cgFloat)
            make.height.equalTo(233)
        }
        
        var lastItem:ST_MemberSubscriberTopDescribeView?
        for item in self.data_array {
            
            let v = ST_MemberSubscriberTopDescribeView()
            
            v.model = item
            
            scroll_content_view.addSubview(v)
            
            v.snp.makeConstraints { (make) in
                make.top.bottom.equalToSuperview()
                make.width.equalTo(root_view_width)
                if let last = lastItem{
                    make.left.equalTo(last.snp.right)
                }else{
                    make.left.equalToSuperview()
                }
            }
            
            lastItem = v
        }
        
        
        root_view.addSubview(title_btn)
        title_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(15)
            make.height.equalTo(25)
        }
        
        root_view.addSubview(pay_item_view1)
        root_view.addSubview(pay_item_view3)
        root_view.addSubview(pay_item_view2)
        
        pay_item_view2.snp.makeConstraints { (make) in
            make.width.equalTo(pay_item_selected_width)
            make.height.equalTo(180)
            make.left.equalTo(pay_item_view1.snp.right)
            make.top.equalToSuperview().offset(76+179)
        }
        
        
        pay_item_view1.snp.makeConstraints { (make) in
            make.height.equalTo(pay_item_view2)
            make.width.equalTo(pay_item_normal_width)
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(pay_item_view2)
        }
        
        pay_item_view3.snp.makeConstraints { (make) in
            make.height.equalTo(pay_item_view2)
            make.width.equalTo(pay_item_normal_width)
            make.left.equalTo(pay_item_view2.snp.right)
            make.top.equalTo(pay_item_view2)
        }
        
        root_view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(36)
            make.centerX.equalToSuperview()
            make.top.equalTo(pay_item_view2.snp.bottom).offset(30)
        }
        
        root_view.addSubview(cancel_btn)
        cancel_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(30)
            make.centerX.equalToSuperview()
            make.top.equalTo(confirm_btn.snp.bottom).offset(7)
        }
        
        root_view.addSubview(pageControl)
        pageControl.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(179+54-4)
            make.height.equalTo(5+10)
//            make.width.equalTo(100)
        }
        
        root_view.addSubview(helper_btn)
        helper_btn.snp.makeConstraints { (make) in
            make.width.equalTo(64)
            make.height.equalTo(23)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(16)
        }
        
        self.view.addSubview(purchase_cancel_sub_label)
        purchase_cancel_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(root_view.snp.bottom).offset(24)
        }
        
        self.view.addSubview(purchase_cancel_content_label)
        purchase_cancel_content_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(purchase_cancel_sub_label.snp.bottom)
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
        }
        
        
        request_data()
        
    }
    
    
    @objc fileprivate func click(sender:ST_MemberSubscriberPaymentBaseView){
        
        
        if sender.isSelected{
            return
        }
        
        sender.snp.updateConstraints { (make) in
            make.width.equalTo(pay_item_selected_width)
        }
        
        
        if let last = last_selected_item  {
            sender.bringSubviewToFront(last)
            
            last.snp.updateConstraints { (make) in
                make.width.equalTo(pay_item_normal_width)
            }
            
        }
        self.last_selected_item?.isSelected = false
        sender.isSelected = true
        self.last_selected_item = sender
        
        
        
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        if first_selected == false {
            
            click(sender: pay_item_view2)
            
            first_selected = true
        }
    }
    
    func request_data(){
        
        JVrequest(PH.showApplePriceApi, success: { (json) in
            
            if let list = [ST_JVPayItemViewModel].deserialize(from: json["data"]["member"].rawString()) as? [ST_JVPayItemViewModel]{
                
                if let item = list[safe:0]{
                    
                    item.topTitle = "物有所值"
                    self.pay_item_view1.model = item
                }
                
                if let item = list[safe:1]{
                    item.topTitle = "人气No.1"
                    self.pay_item_view2.model = item
                }
                
                if let item = list[safe:2]{
                    self.pay_item_view3.model = item
                }
            }
            
            print("返回数据：",json["data"]["member"])
            
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    
//    MARK: - Properties
    fileprivate var data_array = [ST_MemberSubscriberItemViewStruct]()
    
    fileprivate var first_selected = false
    
    fileprivate lazy var personal_mask_view:UIVisualEffectView = {

        let blurEffect = UIBlurEffect(style: .dark)
        let control = UIVisualEffectView.init(effect: blurEffect)
        
        return control
        
    }()
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.cornerRadius = 20
        control.backgroundColor = Color.white
        return control
    }()
    
    fileprivate lazy var scrollView:UIScrollView = {
       let control = UIScrollView()
        control.backgroundColor = .clear
        control.showsHorizontalScrollIndicator = false
        control.isPagingEnabled = true
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var pageControl:UIPageControl = {
        let control = UIPageControl()
        control.numberOfPages = ST_BitianSubscribeType.allCases.count
        control.currentPage = 0
        control.pageIndicatorTintColor = UIColor.init(hex: 0xDFE3E9)
        control.currentPageIndicatorTintColor = UIColor.init(hex: 0x333333)
        return control
    }()
    
    fileprivate lazy var scroll_content_view:UIView = {
       let control = UIView()
        control.backgroundColor = .clear
        return control
    }()
    
    
    fileprivate lazy var front_image_view = self.animate_image_view0
    
    fileprivate lazy var behind_image_view = self.animate_image_view1
    
    fileprivate lazy var animate_images:[UIImage] = {
        
        return [ST_ImageUtils.imageName("Subscriber_background_icon_0"),ST_ImageUtils.imageName("Subscriber_background_icon_1"),ST_ImageUtils.imageName("Subscriber_background_icon_2"),ST_ImageUtils.imageName("Subscriber_background_icon_3"),ST_ImageUtils.imageName("Subscriber_background_icon_4"),ST_ImageUtils.imageName("Subscriber_background_icon_5"),ST_ImageUtils.imageName("Subscriber_background_icon_6"),ST_ImageUtils.imageName("Subscriber_background_icon_7"),ST_ImageUtils.imageName("Subscriber_background_icon_8")].compactMap{$0}
        
    }()
    
    
    
    fileprivate lazy var animate_image_view0:UIImageView = {
        let control = UIImageView()
        control.image = animate_images[0]
        return control
    }()
    
    fileprivate lazy var animate_image_view1:UIImageView = {
        let control = UIImageView()
        control.image = animate_images[1]
        control.alpha = 0
        return control
    }()
    
    
    fileprivate lazy var title_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
      
        control.setTitleForAllStates("开通伴心会员")
        
        control.setTitleColorForAllStates(UIColor.white)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        
        return control
    }()
    
    
    fileprivate let pay_item_normal_width = 100.cgFloat
    
    fileprivate let pay_item_selected_width = 125.cgFloat
    
    fileprivate var last_selected_item:ST_MemberSubscriberPaymentBaseView?
    
    fileprivate lazy var pay_item_view1:ST_MemberSubscriberPaymentView = {
        let control = ST_MemberSubscriberPaymentView()
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var pay_item_view2:ST_MemberSubscriberPaymentView = {
        let control = ST_MemberSubscriberPaymentView()
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var pay_item_view3:ST_MemberSubscriberBasicsPaymentView = {
        let control = ST_MemberSubscriberBasicsPaymentView()
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var confirm_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("继续")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 18
        control.add_touch_up(insideTarget: self, action: #selector(confirm_handle))
        return control
    }()
    
    fileprivate lazy var cancel_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("不用了，谢谢")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#999999")!)
        control.add_touch_up(insideTarget: self, action: #selector(cancel_handle))
        return control
    }()
    
    fileprivate lazy var helper_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("支付帮助")
        control.borderColor = .white
        control.borderWidth = 1
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = .clear
        control.cornerRadius = 11
        control.add_touch_up(insideTarget: self, action: #selector(helper_handle))
        return control
    }()
    
    fileprivate lazy var purchase_cancel_sub_label:UILabel = {
        let control = UILabel.init()
        control.text = "自动订阅，随时取消"
        control.textColor = Color.init(hexString: "#999999")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var purchase_cancel_content_label:UITextView = {
        
        let control = UITextView.init()
        
        control.delegate = self
        control.isEditable = false
        control.isScrollEnabled = false
        
        control.backgroundColor = Color.clear
        
        control.tintColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        
        control.textAlignment = .center
        
        
        
        let attrString = NSMutableAttributedString(string: "购买订阅的费用将从你的iTunes账户收取，到期前24小时会自动扣费并续订服务，购买后可随时前往iTunes商店的设置页面取消订阅。点击购买即表示同意")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        attrString.append(privacy_link_attribute)
        
        
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = .center
        paragraph.lineSpacing = 3
        
        let centerAttr : [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle:paragraph]
        attrString.addAttributes(centerAttr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        return control
    }()
    
    
    lazy var privacy_link_attribute:NSAttributedString = {
        
        let attr = "《服务条款》".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!),Attribute.link(URL.init(string: PH.serviceProtocolURL)!)])
        
        let attr1 = "及".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))])
        
        let attr2 = "《隐私政策》".withAttributes([Attribute.font(Font.systemFont(ofSize: 10)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!),Attribute.link(URL.init(string: PH.privacyProtocolURL)!)])
        
        attr.append(attr1)
        
        attr.append(attr2)
        
        return attr
    }()
    
    
//    MARK: - success Toast properties
    fileprivate lazy var success_root_view:UIView = {
       let control = UIView()
        control.cornerRadius = 20
        control.backgroundColor = Color.white
        return control
    }()
    
    fileprivate lazy var success_title_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleForAllStates("支付成功")
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        
        control.semanticContentAttribute = .forceRightToLeft
        
        control.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        
        return control
    }()
    
    fileprivate lazy var success_center_image_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("首页_img_支付成功")
        return control
    }()

    fileprivate lazy var success_center_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "真棒！支付成功！")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hexString: "#333333")!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    
    fileprivate lazy var success_center_sub_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "开始尽情地玩耍吧~")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular),.foregroundColor: UIColor.init(hex: 0x666666)!]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    fileprivate lazy var success_ok_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("好的")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 18
        control.add_touch_up(insideTarget: self, action: #selector(cancel_handle))
        return control
    }()
    
//    MARK: - Event
    
    var cancel_closure:(()->())?
    
    @objc func cancel_handle(){
        
        if isMaskView {
            
            cancel_closure?()
            
            return
        }
        
        goback_previous_controller(animated: true) {
         
            self.cancel_closure?()
            
        }
        
    }
    
    @objc func helper_handle(){
        
        guard let url = URL(string: PH.helpPayHtml.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) else { return  }
        
        let vc = ST_RegistStepHelperController()
        
        vc.url = url
        
        vc.hiddenfeedback = true
        
        GlobalPresent(toController: vc)
        
    }
    
    @objc func confirm_handle(){
        
        guard let itemControl = self.last_selected_item else { return  }
        
        let item_model = itemControl.model
        
        let str = item_model.descr+item_model.original_price.int.string+"元"+item_model.ename
        
        ST_BTGlobalDataCenter.shared.payMemberPage(paramValue: str)
        
        ST_MaidWayManager.shared.doWay(id: itemControl.model.id, delegate: self)
        
    }
    
    
    func transaction_succeed(){
        
        
        root_view.isHidden = true
        
        view.addSubview(success_root_view)
        success_root_view.snp.makeConstraints { (make) in
            make.width.equalTo(320)
            make.height.equalTo(420)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        success_root_view.addSubview(success_title_btn)
        success_title_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(33)
            make.width.equalTo(170)
            make.height.equalTo(30)
        }
        
        success_root_view.addSubview(success_center_image_view)
        success_center_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_title_btn.snp.bottom).offset(14)
            make.width.equalTo(180)
            make.height.equalTo(120)
        }
        
        success_root_view.addSubview(success_center_label)
        success_center_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_image_view.snp.bottom).offset(27)
        }
        
        success_root_view.addSubview(success_center_sub_label)
        success_center_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_label.snp.bottom).offset(5)
        }
        
        
        success_root_view.addSubview(success_ok_btn)
        success_ok_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(36)
            make.centerX.equalToSuperview()
            make.top.equalTo(success_center_sub_label.snp.bottom).offset(44)
        }
        
    }
    
    
    
    fileprivate var currentPage = 0{
        didSet{
            self.pageControl.currentPage = self.currentPage
        }
    }
    
    fileprivate var last_content_offset = 0.cgFloat
}



extension ST_MemberSubscriberController:UITextViewDelegate{
    
    
    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = URL.absoluteString
        
        vc.titleStr = PH.serviceProtocolURL == vc.urlStr ? "服务条款" : "隐私政策"
        
        GlobalPresent(toController: vc)
        
        return false
    }
    
}

//MARK: - UIScrollViewDelegate
extension ST_MemberSubscriberController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        stoppedScrolling()
    }
    
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
        print("scrollViewWillEndDragging----scrollViewWillEndDragging")
        
        scrollView.isUserInteractionEnabled = false
        
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        if decelerate == false{
            stoppedScrolling()
        }
    }

    func stoppedScrolling(){
        
        
        let integerPart = (scrollView.contentOffset.x/root_view_width).int
        
        if currentPage != integerPart{

            front_image_view.alpha = 0
            
            behind_image_view.alpha = 1
            
            swap(&front_image_view, &behind_image_view)
            
            print("交换-Will---")
            
            currentPage = integerPart
            
        }else{
            print("不交换----")
        }
        
        scrollView.isUserInteractionEnabled = true
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    

        if scrollView.contentOffset.x < 0{
            return
        }

        let offset = scrollView.contentOffset.x.truncatingRemainder(dividingBy: root_view_width)
        
        var percent = offset/root_view_width
        
        let width = scrollView.frame.size.width
        
        let pageFloat = (scrollView.contentOffset.x + (0.5 * width)) / width
        
        
        let currentFloat = self.currentPage.cgFloat + 0.5
        
//
        if pageFloat > currentFloat{
            
            print("看下一页")
            
            if let img = animate_images[safe:self.currentPage+1]{
                behind_image_view.image = img
            }
            
            
        }else if pageFloat < currentFloat{
            
            print("看上一页")
            
            percent = 1 - percent
            
            if let img = animate_images[safe:self.currentPage-1]{
                behind_image_view.image = img
            }
        }
        
        print("当前页精准判断---pageFloat:",pageFloat)
        
//        print("前置Image百分比",1 - percent)
        
//        print("后置Image百分比",percent)
        
        let isInteger = percent.floor == percent
        
        if isInteger{
            
            print("不生效")
            
            return
        }
        
        front_image_view.alpha = 1 - percent
        
        behind_image_view.alpha = percent
        
    }
    
}
